﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using VerifyArgs;

namespace Corvus
{
    public class AggregateRootTypeConverter : TypeConverter
    {

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            Verify.Args(new { destinationType }).NotNull();
            if (typeof(IEntityReference).IsAssignableFrom(destinationType)) return true;
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            Verify.Args(new { destinationType }).NotNull();
            if (value == null) return null;

            if (!typeof(IAggregateRoot).IsInstanceOfType(value)) return base.ConvertTo(context, culture, value, destinationType);
            var agg = (IAggregateRoot)value;
            if (destinationType.IsGenericType)
            {
                Type concrete = typeof(EntityReference<>).MakeGenericType(destinationType.GetGenericArguments().First());
                return Activator.CreateInstance(concrete, agg);
            }
            else
            {
                return new EntityReference { Id = agg.Id };
            }

        }


    }
}
